const errorTypes = require('../constants/error-types')
const userService = require('../services/user.service')
const md5password = require('../utils/password-handle')

// 验证用户的注册行为是否正确
const verifyUser = async (ctx, next) => {
	// 获取用户名和密码
	const { name, password } = ctx.request.body

	// 判断用户名或者密码是否为空
	if (!name || !password) {
		const error = new Error(errorTypes.USERNAME_OR_PASSWORD_IS_REQUIRED)
		return ctx.app.emit('error', error, ctx)
	}

	// 判断当前注册的用户是否被注册过
	const result = await userService.getUserByName(name)
	if (result.length) {
		const error = new Error(errorTypes.USER_ALREADY_EXISTS)
		return ctx.app.emit('error', error, ctx)
	}

	await next()
}

const handlePassword = async (ctx, next) => {
  const { password } = ctx.request.body
  // console.log('pappa: ', password);
  ctx.request.body.password = md5password(password)
  // console.log('pappdpa: ', ctx.request.body.password);
	await next()
}

module.exports = {
	verifyUser,
	handlePassword,
}
